#!/usr/bin/env python
########################################
#
# alert-poller.py - Alert Poller
#
########################################

from socket import *
import simplejson as json
import os
import sys
import logging
import stomp

__program__ = 'alert-poller'
__version__ = '1.0.1'

BROKER_LIST  = [('localhost', 61613)] # list of brokers for failover                                                                                                                                                                                                 
ALERT_QUEUE  = '/queue/alerts'

HOST = 'devmonsvr01'
PORT = 29876
ADDR = (HOST,PORT)
BUFSIZE = 4096

#LOGFILE = '/var/log/alerta/alert-poller.log'
#PIDFILE = '/var/run/alerta/alert-poller.pid'
#CONFFILE = '/opt/alerta/conf/alert-poller.yaml'
LOGFILE = '/home/dnanini/alerta/alert-poller.log'
PIDFILE = '/home/dnanini/alerta/alert-poller.pid'
CONFFILE = '/home/dnanini/alerta/conf/alert-poller.yaml'

class MessageHandler(object):                                                                                                                                                                                                                                            
                                                                                                                                                                                                                                                                         
    def on_error(self, headers, body):                                                                                                                                                                                                                                   
        logging.error('Received an error %s', body)                                                                                                                                                                                                                      
                                                                                                                                                                                                                                                                         
    def on_disconnected(self):                                                                                                                                                                                                                                           
        global conn                                                                                                                                                                                                                                                      

        logging.warning('Connection lost. Attempting auto-reconnect to %s', ALERT_QUEUE)                                                                                                                                                                                 
        conn.start()                                                                                                                                                                                                                                                     
        conn.connect(wait=True)                                                                                                                                                                                                                                          
        conn.subscribe(destination=ALERT_QUEUE, ack='auto')  

def main():
    cli = socket( AF_INET,SOCK_STREAM)
    cli.connect((ADDR))
    logging.info('Connecting to %s port %s' % (ADDR))

    # Write pid file if not already running
    if os.path.isfile(PIDFILE):
        pid = open(PIDFILE).read()
        try:
            os.kill(int(pid), 0)
            logging.error('Process with pid %s already exists, exiting', pid)
            sys.exit(1)
        except OSError:
            pass
    file(PIDFILE, 'w').write(str(os.getpid()))

    # Connect to message broker
    logging.info('Connect to broker')
    try:
        conn = stomp.Connection(
                   BROKER_LIST,
                   reconnect_sleep_increase = 5.0,
                   reconnect_sleep_max = 120.0,
                   reconnect_attempts_max = 20
               )
        conn.set_listener('', MessageHandler())
        conn.start()
        conn.connect(wait=True)

    except Exception, e:
        logging.error('Stomp connection error: %s', e)
        sys.exit(1)

    # 
    while True:
        data = cli.recv(BUFSIZE)
        print data
        logging.info('Recieve data: %s' % data)

if __name__ == '__main__':
      main()
